package com.anti.modular.sys.log.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.anti.jdbc.DBUtils;
import com.anti.jdbc.support.page.PageParam;
import com.anti.jdbc.support.page.PageResult;
import com.anti.modular.sys.log.entity.SysOpLog;
import com.anti.modular.sys.log.param.SysOpLogParam;
import com.anti.modular.sys.log.service.SysOpLogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @Description TODO
 * @Author anTi
 * @Date 2021-3-1
 */
@Service
public class SysOpLogServiceImpl implements SysOpLogService {
    @Resource
    DBUtils dbUtils;

    @Override
    public PageResult page(PageParam pageParam, SysOpLogParam sysOpLogParam) {
        StringBuilder sb=new StringBuilder("select * from sys_op_log where 1=1 ");
        ArrayList<Object> params = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(sysOpLogParam)) {
            //根据名称模糊查询
            if (ObjectUtil.isNotEmpty(sysOpLogParam.getName())) {
                sb.append(" and name like ?");
                params.add("%"+sysOpLogParam.getName()+"%");
            }
            //跟据访问类型（字典 1登入 2登出）查询
            if (ObjectUtil.isNotEmpty(sysOpLogParam.getOpType())) {
                sb.append(" and op_type = ?");
                params.add(sysOpLogParam.getOpType());
            }
            //根据是否成功查询
            if (ObjectUtil.isNotEmpty(sysOpLogParam.getSuccess())) {
                sb.append(" and success = ?");
                params.add(sysOpLogParam.getSuccess());
            }
            // 根据时间范围查询
            if (ObjectUtil.isAllNotEmpty(sysOpLogParam.getSearchBeginTime(), sysOpLogParam.getSearchEndTime())) {
                sb.append(" and date_format (op_time,'%Y-%m-%d') >= date_format('" + sysOpLogParam.getSearchBeginTime() + "','%Y-%m-%d')");
                sb.append(" and date_format (op_time,'%Y-%m-%d') <= date_format('" + sysOpLogParam.getSearchEndTime() + "','%Y-%m-%d')");
            }
        }
        sb.append(" order by op_time desc");
        return dbUtils.query(pageParam,sb.toString(),params.toArray());
    }

    @Override
    public void delete() {
        dbUtils.execSql("delete from sys_op_log");
    }

    @Override
    public void save(SysOpLog sysOpLog) {
        dbUtils.insert(sysOpLog);
    }
}
